package itqf.service;

import itqf.dao.UserDaoImpl;
import itqf.entity.Users;
import itqf.service.impl.UserService;
import itqf.utils.EmailUtils;

import java.net.Inet4Address;
import java.util.Base64;

/**
 * com.itqf.service
 * 2020/9/14
 */
public class UserServiceImpl implements UserService {
    UserDaoImpl userDao = new UserDaoImpl();
    @Override
    public Users login(String username, String upassword) {
        Users user = userDao.findUser(username, upassword);
        if(user!=null){
            return user;
        }
        return null;
    }

    @Override
    public int insert(Users user) {
        int insert = userDao.insert(user);
        try{
            if(insert>0){
                //发送邮箱
                String title = "小米商城激活账户";
                String ip = Inet4Address.getLocalHost().getHostAddress();
                String c = Base64.getEncoder().encodeToString(user.getUcode().getBytes());
                System.out.println(c);
                String url = "http://"+ip+":8080/userController?method=activeAccount&c="+c;
                String content = user.getUsername()+":<br>您好,<a href='"+url+"'>请点击此链接激活账户</a>";
                EmailUtils.sendEmail(title,content,user.getUemail());
            }
        }catch(Exception e){
            e.getLocalizedMessage();
        }
        return insert;
    }

    @Override
    public int activeAccount(String c) {
        int i = userDao.activeAccount(c);
        if(i==0){
            userDao.updateAccount(c);
        }
        return i;
    }

    @Override
    public boolean checkName(String username) {
        Users users = userDao.checkName(username);
        if(users!=null)
        {
            return true;
        }else{
            return false;
        }
    }
}
